Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
Hello! I am not able to run the code below in the Udacity Workspace. However it works just fine in Colab with GPU. Here's my notebook, re-run without GPU.
# TODO: Make all necessary imports.
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub
tfds.disable_progress_bar()
import warnings
warnings.filterwarnings('ignore')
#Set high resolution display for plots
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import matplotlib.pyplot as plt
import logging
logger = tf.get_logger()
import json
from PIL import Image
# To keep keras results reproducible
tf.random.set_seed(1234)
print('Using:')
print('TensorFlow version:', tf.__version__)
print('tf.keras version:', tf.keras.__version__)
print('Hub version:', hub.__version__)
print('Running on GPU' if tf.config.list_physical_devices('GPU') else 'GPU device not found. Running on CPU')
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# TODO: Load the dataset with TensorFlow Datasets.
dataset, dataset_info = tfds.load('oxford_flowers102', as_supervised=True, with_info=True)
# TODO: Create a training set, a validation set and a test set.
training_set, testing_set, validation_set = dataset['train'], dataset['test'], dataset['validation']
dataset_info
# Check dataset is a dictionary
type(dataset)
# Print keys of dataset
dataset.keys()
print(len(dataset['test']))
print(len(dataset['train']))
# TODO: Get the number of examples in each set from the dataset info.
num_training_examples = dataset_info.splits['train'].num_examples
num_testing_examples = dataset_info.splits['test'].num_examples
num_validation_examples = dataset_info.splits['validation'].num_examples
total = num_training_examples + num_testing_examples + num_validation_examples
print('There are {:,} images in the training set'.format(num_training_examples))
print('There are {:,} images in the testing set'.format(num_testing_examples))
print('There are {:,} images in the validation set'.format(num_validation_examples))
print('Total = {:,} images'.format(total))
# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes
print('\nThere are {:,} classes in our dataset'.format(num_classes))
# TODO: Print the shape and corresponding label of 3 images in the training set.
print('Shapes and Labels of 3 images in training set:\n')
for image, label in training_set.take(3):
print('shape:', image.shape)
print('image type: ', image.dtype)
print('label type:', label.dtype)
print('label:', label.numpy())
print('\n')
The images have different shapes. Image dtype is uint8 (0-255 pixels) whereas label dtype is int64 (integers value)
# TODO: Plot 1 image from the training set.
for image, label in training_set.take(1):
image = image.numpy().squeeze()
label = label.numpy() + 1 # Need to add 1 to the indice to get the label
# Plot the image
plt.imshow(image, cmap = plt.cm.binary)
plt.colorbar()
#Display plot
plt.show()
# Set the title of the plot to the corresponding image label
print(' Label of this image is: {}'.format(label))
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
with open('label_map.json', 'r') as f:
class_names = json.load(f)
class_names.keys()
# retrieve the value associated with sample class_name key
class_names['73']
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding class name.
for image, label in training_set.take(1):
image = image.numpy().squeeze()
label = label.numpy() + 1
# Plot the image
plt.imshow(image, cmap = plt.cm.binary)
plt.colorbar()
#Display plot
plt.show()
# Set title of plot
print('Label of this image: {}'.format(label))
print('Class name of this image: {}'.format(class_names[str(label)]))
# TODO: Create a pipeline for each set.
# A function to normalize images:
# 1. Re-cast image from utf8 to float32 datatype
# 2. Since images are now of different sizes (as seen in our sample of 3 images ), reshape them to 224x 224
# 3. Rescale pixel values (range 0-255) to range (0,1)
IMAGE_RES = 224
def normalize(image, label):
image = tf.cast(image, tf.float32)
image = tf.image.resize(image, (IMAGE_RES, IMAGE_RES))/255.0
return image, label
BATCH_SIZE = 64
training_batches = training_set.cache().shuffle(num_training_examples//4).map(normalize).batch(BATCH_SIZE).prefetch(1)
testing_batches = testing_set.cache().map(normalize).batch(BATCH_SIZE).prefetch(1)
validation_batches = validation_set.cache().map(normalize).batch(BATCH_SIZE).prefetch(1)
# Confirm that each batch has 64 images of 224 x 224 with 3 channels.
for image, label in training_batches.take(1):
print('training batch 1:')
print(image.shape)
print(image.dtype)
print(label.numpy() +1 )
for image, label in testing_batches.take(1):
print('\ntesting batch 1:')
print(image.shape)
print(image.dtype)
print(label.numpy() + 1)
for image, label in validation_batches.take(1):
print('\ntraining batch 1:')
print(image.shape)
print(image.dtype)
print(label.numpy() + 1)
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
# TODO: Build and train your network using transfer learning
# Use MobileNet pre-trained classifier model URL from TF Hub
url= 'https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/4'
# Set up Keras layer with the pre-trained Hub model. Input shape is the shape of our RGB image (224 x 224 x 3 channels)
feature_extractor = hub.KerasLayer(url, input_shape=(224, 224, 3))
# Freeze weights and biases in the pre-trained Hub model to prevent model from re-training
feature_extractor.trainable = False
# Build and train the model with the feature_extractor and an output layer with 102 classes (102 flower labels) and softmax activation (output predicted probabilities associated with each label)
model = tf.keras.Sequential([
feature_extractor,
tf.keras.layers.Dense(102, activation ='softmax')
])
#Print model summary
model.summary()
# Compile model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy', # predicting multi-classes with integers as labels
metrics=['accuracy'])
# Evaluate loss and accuracy on one training batch before training. Accuracy is expected to be very low before training
for image, label in training_batches.take(1):
loss, accuracy = model.evaluate(image, label)
print('\nLoss before training: {:,.3f}'.format(loss))
print('Accuracy before training: {:.3%}'.format(accuracy))
Accuracy before training is 0%, very low indeed!
# Train model for up to indicated number of epochs callback options
# This early stopping callback will stop the training when there is no improvement in
# the quantity to monitor (val loss) for three consecutive epochs or when the min_delta is 0.001
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', min_delta = 0.001, patience=3)
EPOCHS = 100 # number of times the training is passed through the model
history = model.fit(training_batches,
epochs = EPOCHS,
validation_data = validation_batches,
callbacks = [early_stopping])
# Check when did the early_stopping stop
len(history.history['loss'])
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']
training_loss = history.history['loss']
validation_loss = history.history['val_loss']
epochs_range=range(len(training_accuracy))
plt.figure(figsize=(12, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
From the plot, training and validation accuracies quickly hit plateaus (more than 90% and 70% respectively) wtihin 10 Epochs of training. The model eventually stopped training at EPOCH 72 using the early stopping parameters specified.
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
# Make predictions on a batch of testing set images
for image, label in testing_batches.take(1):
ps = model.predict(image)
images = image.numpy().squeeze()
labels = label.numpy() + 1
# Display predictions on a batch of testing set images
plt.figure(figsize=(12,18))
for n in range(30):
plt.subplot(6,5,n+1)
plt.imshow(images[n])
# To display titles of images that are correctly predicted in green, and red otherwise
color = 'green' if np.argmax(ps[n]) == labels[n] else 'red'
plt.title(str(labels[n]) + ": " + class_names[str(labels[n])], color = color )
plt.axis('off')
# TODO: Print the loss and accuracy values achieved on the entire test set.
# Evaluate model on all testing batches
score = model.evaluate(testing_batches)
#Print the loss and accuracy values
print('Test loss:', score[0])
print('Test accuracy:', score[1])
My model achieves an accuracy of 77.4% on the test images. There is scope to improve the model further but for now, we will work with the model
# Predict labels from testing_batches
predictions = model.predict(testing_batches)
print('Type of predictions object', type(predictions))
print('Number of elements in predictions object:', len(predictions))
print('Shape of predictions object: ', predictions.shape)
# Index of the max probability of first image
np.argmax(predictions[0])
The columns are zero-based indices. But the dictionary keys start from 1. Therefore to get the label number corresponding to the dictionary, we need to +1 to the index
# Max predicted Probability value of first image
predictions[0][np.argmax(predictions[0])]
Predictions are in 6149 x 102 numpy array. THe 6149 rows represent each image, and the 102 columns represent the probabilties of each of the 102 possible flower classes. The predicted label for the image is given by the maxinum value in each row and can be retrieved with np.argmax.
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
# TODO: Save your trained model in working directory as a Keras model.
# Append timestamp to model
import time
t = time.time()
saved_keras_model_filepath = './my_model_{}.h5'.format(int(t))
model.save(saved_keras_model_filepath)
ls
Load the Keras model you saved above.
# TODO: Load the Keras model from working directory
saved_keras_model_filepath = 'my_model_1632117166.h5'
reload_keras_saved_model = tf.keras.models.load_model(saved_keras_model_filepath,
custom_objects={'KerasLayer': hub.KerasLayer}) # `custom_objects` tells keras how to load a `hub.KerasLayer`
reload_keras_saved_model.summary()
# Sanity check: to confirm my saved model make the same predictions as before
for image, label in testing_batches.take(1):
prediction_1 = model.predict(image)
prediction_2 = reload_keras_saved_model.predict(image)
difference = np.abs(prediction_1 - prediction_2)
print(difference.max()) # Should be 0 if same predictions
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
# TODO: Create the process_image function
def process_image(image):
image = tf.convert_to_tensor(image) # convert image numpy object to tensorflow object
image = tf.cast(image, tf.float32)
image = tf.image.resize(image, (224, 224)) # reshape image to 224 x 224
image = image/255 # normalize pixels (0-255) to (0-1)
image = image.numpy() # convert tf object to numpy array
return image
To check your process_image function we have provided 4 images in the ./test_images/ folder:
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
from PIL import Image
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)
processed_test_image = process_image(test_image)
# Confirm that the test image processing was successful
print(test_image.shape)
print(test_image.dtype)
print(processed_test_image.shape)
print(processed_test_image.dtype)
# Plot the raw and processed test image
fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
# TODO: Create the predict function
def predict(image_path, model, top_k =5):
# Load image using PIL Image method
im = Image.open(image_path)
im = np.asarray(im) # convert image to numpy array
# Process image using process_image function. Outputs image with shape (224, 224, 3 )
im = process_image(im)
# Make prediction using trained model
im = np.expand_dims(im, axis =0) # convert image to (0,224,224,3)
predictions = model.predict(im).squeeze() # Prediction is in 1D numpy array of probabilities
## Retrieve Top N classes and their probabilities
indices = np.argsort(-predictions)[:top_k]
labels = indices +1
probs = predictions[indices]
# return flower names from class_names dictionary. Add 1 because the dictionary keys start from 1 wheras the indices start from 0
classes = [class_names[str(i)] for i in labels]
return classes, probs
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.
# TODO: Plot the input image along with the top 5 classes
# Define model to use
model = reload_keras_saved_model
# Define path of image
image_path ='./test_images/cautleya_spicata.jpg'
# Make predictions
classes, probs = predict(image_path, model)
# Plot the image and predictions side by side
im = Image.open(image_path) # Open image with PIL.image
test_image = np.asarray(im) # Convert image to array
fig, (ax1, ax2) = plt.subplots(figsize=(10,5), ncols=2)
ax1.imshow(test_image)
ax1.set_title(image_path)
ax2.barh(classes, probs)
ax2.set_title('Predictions & their probabilities')
#Display plot
plt.tight_layout()
plt.show()
print("Top N predictions:")
print("classes: ", classes)
print("Probabilities: ", np.round(list(probs), 3))
# Repeat but looping through each image in folder
import glob
files = glob.glob('./test_images/*')
for image_path in files:
# Make predictions
classes, probs = predict(image_path, model, top_k=5)
# Plot the image and predictions side by side
im = Image.open(image_path) # Open image with PIL.image
test_image = np.asarray(im) # Convert image to array
fig, (ax1, ax2) = plt.subplots(figsize=(10,5), ncols=2)
ax1.imshow(test_image)
ax1.set_title(image_path)
ax2.barh(classes, probs)
ax2.set_title('Predictions & their probabilities')
#Display plot
plt.tight_layout()
plt.show()
print("Top N predictions")
print("Classes: ", classes)
print("Probabilities: ", np.round(list(probs), 3))
From the results of the test images evaluation, the model predicted 3 out of 4 images with probabilities of almost 1.
However, the prediction was less convincing for the orange dahlia test image. The model predicted marigold as #1 with a probability of ~0.54 followed closely by orange dahlia with a probability of ~0.4.
The results (3/4 images accurately predicted) are not unexpected because when we built and test the model earlier, we found that model had an accuracy of ~77%.
!jupyter nbconvert --to html Project_Image_Classifier_Project 2.ipynb